/*
 * MIT License
 *
 * Copyright (c) 2023-present, tangli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package tony.web.auth.jwt.autoconfigure

import java.time.Duration
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.context.properties.bind.DefaultValue
import org.springframework.context.annotation.Bean
import tony.core.PROJECT_GROUP
import tony.core.utils.throwIfNullOrEmpty
import tony.web.auth.IAuthService
import tony.web.auth.jwt.JwtAuthService

/**
 * Web 身份验证 JWT 自动配置
 * @author tangli
 * @date 2025/09/22 17:07
 */
@EnableConfigurationProperties(WebAuthJwtProperties::class)
@AutoConfiguration
private class WebAuthJwtAutoConfiguration {
    @ConditionalOnMissingBean(IAuthService::class)
    @Bean
    private fun jwtAuthService(webAuthJwtProperties: WebAuthJwtProperties): JwtAuthService =
        JwtAuthService(
            webAuthJwtProperties.expiredIn,
            webAuthJwtProperties.secret.throwIfNullOrEmpty("$PROJECT_GROUP.web.auth.jwt.secret 不可为空.")
        )
}

@ConfigurationProperties(
    prefix = "$PROJECT_GROUP.web.auth.jwt",
    ignoreInvalidFields = false,
    ignoreUnknownFields = false
)
private data class WebAuthJwtProperties(
    /**
     * jwt secret
     */
    val secret: String,
    /**
     * 过期时长
     */
    @DefaultValue("1d")
    val expiredIn: Duration,
)
